namespace HZY.Framework.DependencyInjection.Attributes;

/// <summary>
/// 配置文件属性注入
/// </summary>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true, Inherited = true)]
public class AppSettingsAttribute : AopMoAttribute
{
    /// <summary>
    /// 配置节点地址地址
    /// </summary>
    private string OptionNodePath { get; }

    /// <summary>
    /// 配置文件属性注入
    /// </summary>
    /// <param name="optionNodePath"></param>
    public AppSettingsAttribute(string optionNodePath)
    {
        OptionNodePath = optionNodePath;
    }

    public override void OnSuccess(MethodContext context)
    {
        if (context.RealReturnType == null) return;

        var name = context.Method.Name;
        name = name.Replace("get_", "");
        name = name.Replace("set_", "");

        var configuration = this.GetService<IConfiguration>(context);

        if (configuration == null) return;

        var result = configuration.GetSection(OptionNodePath).Get(context.RealReturnType);
        if (result == null) return;

        context.ReplaceReturnValue(this, result);
    }

}